package creator;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class CodeCreator {
	public static void createSimpleJavaFile(String dir, ObjectInfo o) {
		try {
			String fileName = dir + o.getName() + ".java";
			FileWriter fw = new FileWriter(fileName);
			fw.write("package " + o.getPackageName() + ";\n\n");
			
			List<String> imports = o.getImports();
			for (String i: imports) {
				fw.write("import " + i + ";\n");
			}
			
			fw.write("\npublic class " + o.getName());
			String extendsObject = o.getExtendsObject();
			if (extendsObject != null) {
				fw.write(" extends " + extendsObject);
			}
			fw.write(" {\n");
			
			List<Property> objects = o.getProperties();
			for (Property p: objects) {
				fw.write("    // " + p.getComment() + "\n");
				fw.write("    private " + p.getType() + " " + p.getName() + ";\n\n");
			}
			
			createGetterAndSetter(fw, objects);
			
			fw.write("}\n");
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void createGetterAndSetter(FileWriter fw, List<Property> objects) throws IOException {
		for (Property p: objects) {
			String name = p.getName();
			String head = name.substring(0, 1);
			head = head.toUpperCase();
			String format = head + name.substring(1);
			String type = p.getType();
			fw.write("    public " + type + " get" + format + "() {\n");
			if (type.startsWith("List")) {
				fw.write("        if (" + name + " == null) {\n");
				fw.write("            this." + name + " = new ArrayList<String>();\n");
				fw.write("        }\n");
			}
			fw.write("        return " + name + ";\n    }\n\n");
			
			fw.write("    public void" + " set" + format + "(" + type + " " + name + ") {\n");
			fw.write("        this." + name + " = " + name + ";\n    }\n\n");			
		}
	}

	public static boolean createDir(String destDirName) {
		File dir = new File(destDirName);
		if (dir.exists()) {
			System.out.println("创建目录" + destDirName + "失败，目标目录已存在！");
			return false;
		}
		if (!destDirName.endsWith(File.separator))
			destDirName = destDirName + File.separator;
		// 创建单个目录
		if (dir.mkdirs()) {
			System.out.println("创建目录" + destDirName + "成功！");
			return true;
		} else {
			System.out.println("创建目录" + destDirName + "成功！");
			return false;
		}
	}
	

}
